import { expect } from '@jest/globals';
import * as execa from 'execa';

import { runHvigorAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  IsEnable,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType,
  SignType,
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOption, TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';
import { ProjectBuildProfileModifier } from '../../common/modifier/project-build-profile-modifier';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility,
  },
};

const testTaskOption: TestTaskOption = TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L2).sign(SignType.NoSign).ohpmInstall(IsEnable.Enable).build();

const testCaseFun: TestCaseFun = async (project, taskConfig, record) => {
  const projectRootPath = project.projectRootPath();

  const buildProfileModifier = new ProjectBuildProfileModifier(projectRootPath);
  await buildProfileModifier
    .updateProduct({
      name: 'default',
      buildOption: {
        arkOptions: {
          tscConfig: {
            maxFlowDepth: 2000,
          },
        },
      },
    })
    .output();
  // execa.commandSync('ohpm install --all', { encoding: 'utf-8', cwd: projectRootPath });
  // expect(fs.existsSync(path.resolve(projectRootPath, 'oh_modules', 'library'))).toBeTruthy();

  // 执行 entry 模块 构建
  const commands = '--mode project -p product=default assembleApp --incremental --no-daemon'.split(' ');

  let result = await runHvigorAsync(projectRootPath, commands);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');

  await buildProfileModifier
    .updateProduct({
      name: 'default',
      buildOption: {
        arkOptions: {
          tscConfig: {
            maxFlowDepth: 2001,
          },
        },
      },
    })
    .output();

  result = await runHvigorAsync(projectRootPath, commands);
  expect(result.stdout).toContain('Finished :entry:default@CompileArkTS'); // 增量触发

  await buildProfileModifier
    .updateProduct({
      name: 'default',
      buildOption: {
        arkOptions: {
          tscConfig: {
            maxFlowDepth: 1999,
          },
        },
      },
    })
    .output();
  try {
    result = await runHvigorAsync(projectRootPath, commands);
    // 正常路径走不到这里，预判一个异常
    expect('测试场景执行异常抵达此处').toEqual('测试场景执行正常不该抵达此处');
  } catch (e: any) {
    if (e.constructor.name === 'JestAssertionError') {
      throw e;
    }
    expect(e.stderr).toContain('Error Message: Schema validate failed'); // 检验最小
  }

  await buildProfileModifier
    .updateProduct({
      name: 'default',
      buildOption: {
        arkOptions: {
          tscConfig: {
            maxFlowDepth: 65536,
          },
        },
      },
    })
    .output();
  try {
    result = await runHvigorAsync(projectRootPath, commands);
    // 正常路径走不到这里，预判一个异常
    expect('测试场景执行异常抵达此处').toEqual('测试场景执行正常不该抵达此处');
  } catch (e: any) {
    if (e.constructor.name === 'JestAssertionError') {
      throw e;
    }
    expect(e.stderr).toContain('Error Message: Schema validate failed'); // 校验最大
  }
};

TestCaseBuilder.builder()
  .caseName('SR20241031416729')
  .description('支持设置tsc最大递归回栈')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(testTaskOption)
  .testFun(testCaseFun)
  .load();
